<?php

/*  THIS WAS FROM THE GENERIC FILES APRA STUFF HAS BEEN ADDED BELOW

include_once("cmsConfig.php");

function rAddNodeToTree(&$nodeToAdd, $treeFragment) {

		//if (!is_array($nodeToAdd['children'])) 
		//	$nodeToAdd['children'] = array();
		if (!is_array($treeFragment))
			return null;
			 	
		if (key_exists($nodeToAdd['parent'], $treeFragment)) {

			//add an array for children
			if (!key_exists('children', $nodeToAdd) || !is_array('children', $nodeToAdd) )
				$nodeToAdd['children'] = array();
				
			//return the tree fragment..			
			$treeFragment[ $nodeToAdd['parent'] ]['children'][ $nodeToAdd['id']] = $nodeToAdd;
			return $treeFragment;
		} else {
			foreach ( $treeFragment as $key => $node ) {
				
				if (!is_array($node['children'])) 
					$node['children'] = array();
							
				if (($newTreeFragment = rAddNodeToTree($nodeToAdd, $node['children'])) != null){
					$node['children'] = $newTreeFragment;
					$treeFragment[ $key ] = $node;
					return $treeFragment;
				}
			}
		}
		// 
		return null;
	}
	
	function createTreeFromNodes ( $nodeList ) {
	
		//return ;
		//current list
		// those not in tree yet..
		// rAddNodeToTree
		$treeFragment = array();
		
		//create the parent node
		$superNode = array();
		$superNode['parent'] = null;
		$superNode['children'] = array();
		$superNode['id'] = 0;
		$superNode['value'] = "Index";
		$treeFragment[ $superNode['id'] ]	= $superNode;
				
		$nodeListWorking = array();
		array_push($nodeListWorking, array_shift($nodeList));
		while (count($nodeListWorking) > 0 //&& count($nodeList) > 0
		) {
			
			//if we have added.. we can remove from the working list
			$node = array_shift($nodeListWorking);
			if (!is_null($node)) {
				if (($treeFragment = rAddNodeToTree($node, $treeFragment )) == null) {
					array_push($nodeListWorking, $node);
				}
			}
			if (count($nodeList) > 0 ) {
				array_unshift($nodeListWorking, array_shift($nodeList));
			} else {
				// all allocated.. so now.. we need to try and position those
				// that may not have parents..so we now start marking nodes.
			}
		}
		return $treeFragment;
	}*/

	
include_once("cmsConfig.php");

	function rAddNodeToTree(&$nodeToAdd, $treeFragment) {

		//if (!is_array($nodeToAdd['children'])) 
		//	$nodeToAdd['children'] = array();
		if (!is_array($treeFragment))
			return null;
			 	
		if (key_exists($nodeToAdd['parent'], $treeFragment)) {

			//add an array for children
			if (!key_exists('children', $nodeToAdd) || !is_array('children', $nodeToAdd) )
				$nodeToAdd['children'] = array();
				
			//return the tree fragment..			
			$treeFragment[ $nodeToAdd['parent'] ]['children'][ $nodeToAdd['id']] = $nodeToAdd;
			return $treeFragment;
		} else {
			foreach ( $treeFragment as $key => $node ) {
				
				if (!is_array($node['children'])) 
					$node['children'] = array();
							
				if (($newTreeFragment = rAddNodeToTree($nodeToAdd, $node['children'])) != null){
					$node['children'] = $newTreeFragment;
					$treeFragment[ $key ] = $node;
					return $treeFragment;
				}
			}
		}
		// 
		return null;
	}
	
	function createTreeFromNodes ( $nodeList, $db ) {
	
		//return ;
		//current list
		// those not in tree yet..
		// rAddNodeToTree
		$treeFragment = array();
		
		//create the parent node
		$superNode = array();
		$superNode['parent'] = null;
		$superNode['children'] = array();
		$superNode['id'] = 0;
		$superNode['value'] = "Index";
		$superNode['url'] = '/index.php';
		
		$treeFragment[ $superNode['id'] ]	= $superNode;

		//
		foreach($nodeList as $key=>$value){
			$originalNodeList[$key] = $value['id'];
		}
		array_push($originalNodeList,0);
		//		
		
		$nodeListWorking = array();
		array_push($nodeListWorking, array_shift($nodeList));
		$unalloactedNodeCount = null;
		$unallocatedNodes = array();
		
		while (count($nodeListWorking) > 0 //&& count($nodeList) > 0
		) {
			
			//if we have added.. we can remove from the working list
			$node = array_shift($nodeListWorking);
			
			//url check..
			if (!key_exists('url', $node)) {
				//lookup the url..
				$template = getTemplate($node['template'], $db);
				if (!is_null($template)){
					$url = $template['templateurl'];
					if ($template['requiresdocumentcode']){
						$url .= '?id=' . $node['id'];
						$node['url'] =$url;
					}else{
						$node['url'] =$url;					
					}
				}
			}
			
			//parent check
			if(!in_array($node['parent'], $originalNodeList)) {
				//echo $node['parent']." Doesn't exist <br/>";
				continue;
			}			
			
			if (!is_null($node)) {
				if (($newTreeFragment = rAddNodeToTree($node, $treeFragment )) == null) {
					//miss - put back into the workinglist at the end
					array_push($nodeListWorking, $node);
				} else {
					//hit - assign things correctly.
					$treeFragment = $newTreeFragment;
				}
			}
			if (count($nodeList) > 0 ) {
				array_unshift($nodeListWorking, array_shift($nodeList));
			} else {
				// all allocated.. so now.. we need to try and position those
				// that may not have parents..so we now start marking nodes.
				// get the count of total nodes not allocated. and then tag each node.
				// if the visit count is higher than the total remaining nodes
				// mark it as bungness.
				if (is_null($unalloactedNodeCount)) {
					//if we get here and the un allocated node count is not set.
					// we set it inorder to track the un allocated nodes
					$unalloactedNodeCount = count($nodeListWorking);				
				}
				
				
			}
		}
		return $treeFragment;
	}
	
	
	function getTemplate($templateId, &$db) {
		static $templateCache;// = null;
		if ( is_null($templateCache))
			$templateCache = array();
			
		if (key_exists($templateId, $templateCache) && !is_null($templateCache[$templateId]))
			return $templateCache[$templateId];
			 
		$q = "SELECT documentcode AS id, title AS name, url AS templateurl, inhouse AS requiresdocumentcode FROM content WHERE documentcode=$templateId AND active =1 AND documenttypecode='docWebTemp'";
		
		if ($db->executeQuery($q) && $db->numRows() == 1){
			$templateCache[$templateId] =  $db->nextAssoc();
			return $templateCache[$templateId];
		}
		return null;
	}
	
	function preordNodeListFromTree($tree){
	
		//create the result stack
		$preordList = array();
		
		//put the children onto the stack
		$workingStack = $tree['children'];
		while (count($workingStack) > 0 ) {
			$item = array_pop( $workingStack );
			if (key_exists('children', $item) && count($item['children']) > 0){
				if (is_array($node['children']))
					usort($node['children'], "noderanksort");
				while (count($item['children']) > 0 ) {
					array_push($workingStack, array_pop($item['children']));//push me pull you.. all hail the seuss
				}
				//remove the children array
				unset($item['children']);
			}
			array_push($preordList, $item );
		}
		return $preordList;
	}

	
	function pathToNodeInTree($nid, $node){
		$stack = array();
		rPathToNodeInTree($nid, $node, $stack);
		return $stack;
	}
	
	function rPathToNodeInTree($nid,$node,&$stack) {
		if ($nid== $node['id']) {
			return $node['id'];
		}
		
		if (key_exists('children', $node) && is_array($node['children'])){
			if (is_array($node['children']))
				usort($node['children'], "noderanksort");
			foreach($node['children'] as $n) {
				$nr = rPathToNodeInTree($nid, $n, $stack);
				if (!is_null($nr)){
					array_unshift($stack, $n['id']);
					return $nr['id'];
				}
			}
		}
		return null;
	}
	
	function noderanksort($nodea, $nodeb){
			if (!is_array($nodea) || !key_exists('rank', $nodea) || !is_numeric($nodea['rank'])) $ranka = 2147483647; else $ranka = $nodea['rank'];
			if (!is_array($nodeb) || !key_exists('rank', $nodeb) || !is_numeric($nodeb['rank'])) $rankb = 2147483647; else $rankb = $nodeb['rank'];
			return ( $ranka == $rankb ) ? 0 : (($ranka > $rankb) ? 1 : -1);
	}
	
	function printMenuHtml($node, $expandMenu=false, $depth=0) {
		$tabs = "";
		for ($i=0; $i< $depth; $i++){
			$tabs .= "\t";
		}
		$style = (!$expandMenu && $depth > 0) ?  'style="display: none;"' : '';
		echo "$tabs<ul id=\"n". $node['id'] ."\" $style rank=\"" . $node['rank'] . "\">\n";
		
		if ( !is_null($node['children']) && is_array($node['children']) )
			usort($node['children'], "noderanksort");
			
		foreach ( $node['children'] as $key  => $value) {
			$hasChildren = (key_exists('children', $value) && count($value['children']) > 0 );
			//$onClick = $hasChildren ? "onClick=\"javascript:toggleMenu('uln" . $value['id'] . "');return false;\"" : '';
			$onClick = null;
			$url = (key_exists('url', $value) && strlen($value['url']) >0) ? ($value['url']) :"#";
			echo "$tabs\t<li id=\"lin". $value['id'] ."\" rank=\"" . $value['rank'] . "\" ><a id=\"an". $value['id'] ."\" href=\"$url\" $onClick>"  . $value['value']. "</a>";
			if ($hasChildren) {
				echo "\n";
				printMenuHtml($value, $expandMenu, $depth + 2);
				echo "$tabs\t";
			}
			echo "</li>\n";
		}
		echo "$tabs</ul>\n";
	}
	
	
	function &getRawMenuNodes(&$db) {
		$rawNodes = array();
	
		$sourceQuery="SELECT documentcode as id, headline as value, categorycode as parent, url AS template, restricted AS rank FROM content WHERE documenttypecode='docWebPage' AND categorycode != -1 Order by restricted + 0";
		if ($sourceQuery != null && $db->canExecuteQueries() 
			&&  $db->executeQuery(magicClean($sourceQuery, false)) 
			&& ($db->numRows() > 0)) {
			while (($row = $db->nextAssoc())){
				array_unshift($rawNodes, $row);
			}
		}
		
		// attach various sub nodes  here..
		
		//test node adding

		//Music Users - Industry
		$sourceQuery="SELECT documentcode as id, title as value, restricted AS rank FROM content WHERE documenttypecode='docInd' AND active=1 ORDER BY restricted + 0";
		if ($sourceQuery != null && $db->canExecuteQueries() 
			&&  $db->executeQuery(magicClean($sourceQuery, false)) 
			&& ($db->numRows() > 0)) {
			while (($row = $db->nextAssoc())){
				$row['parent'] = 5290;
				$row['template'] = 5329;
				$row['url'] = "/html/industry.php?id=$row[id]";
				array_unshift($rawNodes, $row);
			}

		}

		//Music Users - Industry - Music Uses
		//$sourceQuery="SELECT c1.documentcode as id, c1.title as value, c1.author as parent, c1.restricted AS rank FROM content AS c1 WHERE c1.documenttypecode='docMusicUses' ORDER BY c1.restricted + 0";
		$sourceQuery="SELECT c1.documentcode as id, c1.title as value, c1.author as parent, c1.restricted AS rank FROM content AS c1, content AS c2 WHERE c1.documenttypecode='docMusicUses' AND c1.author=c2.documentcode AND c2.active=1 AND c1.active=1 ORDER BY c1.restricted + 0";
		if ($sourceQuery != null && $db->canExecuteQueries() 
			&&  $db->executeQuery(magicClean($sourceQuery, false)) 
			&& ($db->numRows() > 0)) {
			while (($row = $db->nextAssoc())){
				$row['template'] = 5329;
				$row['url'] = "/html/music_uses.php?id=$row[id]";
				array_unshift($rawNodes, $row);
			}

		}
		
		//FAQ
		/*
		$sourceQuery="SELECT documentcode as id, title as value, restricted AS rank FROM content WHERE documenttypecode='docFAQCat' AND active=1 AND active=1 ORDER BY restricted + 0";
		if ($sourceQuery != null && $db->canExecuteQueries() 
			&&  $db->executeQuery(magicClean($sourceQuery, false)) 
			&& ($db->numRows() > 0)) {
			while (($row = $db->nextAssoc())){
				$row['parent'] = 5401;
				$row['template'] = 5401;
				$row['url'] = "/html/faq.php?id=$row[id]";
				array_unshift($rawNodes, $row);
			}

		}
		*/
		
		/*
		$rawNodes[35]["id"] = 35;
		$rawNodes[35]["value"] = "Industry";
		$rawNodes[35]["parent"] = 5290;
		$rawNodes[35]["template"] = 5329;
		$rawNodes[35]["rank"] = 1;
		$rawNodes[35]["url"] = "/html/industry.php";
		*/

		
		return $rawNodes;
	}
	
	function &getMenuTree(&$db) {
		$tree= array();
		$tree = createTreeFromNodes( getRawMenuNodes($db), $db );
		return $tree;
	}
?>